/*
* @Author: Administrator
* @Date:   2017-12-20 13:55:36
* @Last Modified by:   Administrator
* @Last Modified time: 2018-01-03 11:56:41
*/
const path = require('path')
const express = require('express')
const serverDev = require('./util/dev')
const serverDist = require('./util/dist')
const favicon = require('serve-favicon')
const session = require('express-session')
const bodyParser = require('body-parser')
const axios = require('axios');
const qs = require('qs');
const app = express();
const queryString = require('query-string');
const isDev = process.env.NODE_ENV === 'dev';
var compress = require('compression');
app.use(compress());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(session({
  maxAge: 10 * 60 * 1000,
  name: 'tid',
  resave: false,
  saveUninitialized: false,
  secret: 'I will teach you'
}))
app.use('/user', require('./util/user'))
app.use('/news',function(req, res, next){
  const baseUsl = 'http://jhmaimai.top' + req._parsedOriginalUrl.pathname + '.php'
    + (req._parsedOriginalUrl.search ? req._parsedOriginalUrl.search:'');
  const param = req.method == 'GET' ? queryString.parse(req._parsedOriginalUrl.search) : req.body;
  if (param.userId && (!req.session.user || param.userId != req.session.user.id) ) {
    const response = {
      code: 10,
      message: '请先登录'
    }
    res.send(response);
    res.end();
    return
  }
  axios({
    method: req.method,
    url: baseUsl,
    data: qs.stringify(req.body)
  }).then(result => {
    res.send(result.data)
  }).catch(next)
})
app.use(favicon(path.join(__dirname,'../favicon.ico')))
if (isDev){
  serverDev(app)
}
else{
  serverDist(app)
}

const host = process.env.HOST || '0.0.0.0'
const port = process.env.PORT || 3000

app.listen(port, host, function () {
  console.log(`server is listening on ${host}:${port}`)
})
